package com.mit.common.helper;

import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.StringUtils;



public class DateHelper {

	/**
	 * In MS-SQL the degital of DATETIME is 3.33 MS, in other word, the last
	 * number can only be 0, 3, 7 But in java.util.Date, it can be 0,1,2,3...
	 * This method is to trim the MS to fit MSSQL.
	 * 
	 * @param date
	 * @return
	 */
	public static Date toMSSQLDateTime(Date date){
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		Integer ms = c.get(Calendar.MILLISECOND);
		String pre = StringUtils.left(ms.toString(), 2);
		int l = Integer.parseInt(StringUtils.right(ms.toString(), 1));		
		
		if(l < 3 && l > 0)
			ms = Integer.parseInt(pre + "3");
		else if (l > 3 && l < 7)
			ms = Integer.parseInt(pre + "7");
		else if (l > 7)
			ms = Integer.parseInt(pre + "0") + 10;
		c.set(Calendar.MILLISECOND, ms);
		return c.getTime();
	}
	
	/**
	 * In My-SQL Milliseconds is not supported in DATETIME type.
	 * Via this method, we trim millisecond in the given date.
	 * In this way, the concurrency controller can work
	 */
	public static Date toMYSQLDateTime(Date d){
		Calendar c = Calendar.getInstance();
		c.setTime(d);		
		c.set(Calendar.MILLISECOND, 0);
		return c.getTime();
	}
	

}
